using System;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI;
using RMH.DataAccess;
using RMH.Entities;

namespace RMH.Web.Models.Binders
{
    public class NoteBinder : IModelBinder
    {
        private readonly INoteRepository noteRepository;
        private readonly IPatientRepository patientRepository;

        public NoteBinder(INoteRepository noteRepository, IPatientRepository patientRepository)
        {
            this.noteRepository = noteRepository;
            this.patientRepository = patientRepository;
        }

        public NoteBinder()
        {
            noteRepository = Container.Resolve<NoteRepository>();
            patientRepository = Container.Resolve<PatientRepository>();
        }

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var form = controllerContext.HttpContext.Request.Form;

            Note rv = new Note();

            if (!String.IsNullOrEmpty(form["Id"]))
                rv = noteRepository.GetByID(Int32.Parse(form["Id"]));
            if (!String.IsNullOrEmpty(form["PatientId"]))
                rv.Patient = patientRepository.GetByID(Int32.Parse(form["PatientId"]));
            if (!String.IsNullOrEmpty(form["Note"]))
                rv.Body = form["Note"];
            rv.StaffId = Membership.GetUser().UserName;
            rv.Date = DateTime.Now;

            return rv;
        }
    }
}